import { View, Text,Input,Form,Button,Image,Checkbox,Icon} from '@tarojs/components'
import './index.less'
import { loginaction } from '../../api/user'
import Taro from '@tarojs/taro'
import { connect } from 'react-redux'
import {login} from '../../actions/user'
import { useState,useEffect } from 'react'
function Login (props) {
  const [checked,setChecked] = useState(false)
  const [user_name,setUsername] = useState('')
  const [password,setPassword] = useState('')

  useEffect(()=>{
    if(checked&&user_name!=''&&password!=''){
      document.getElementById('login').style.backgroundColor = '#d02530'
    }
    else{
      document.getElementById('login').style.backgroundColor = '#c95555'
    }
  },[checked,user_name,password])

  const register = () =>{
    Taro.navigateTo({ url: '/pages/register/index' })
  }
  const check = () => {
    setChecked(!checked)
  }

  const login = () => {
    if(checked&&user_name!=''&&password!=''){
      loginaction(user_name,password)
      .then(res=>{
        if(res.data.code=='200'){
          console.log(res.data.data)
          props.userlogin({
            user_id:res.data.data.user.user_id,
            user_name:res.data.data.user.user_name,
            nickname:res.data.data.user.nickname,
            user_photo:res.data.data.user.user_photo,
            token:res.data.data.token
          })
          Taro.switchTab({ url: '/pages/index/index' })
        }
        else if(res.data.code=='400'){
          Taro.showToast({title:'账号密码错误',icon:'none'})
        }
      })
    }
    else if(user_name==''){
      Taro.showToast({title:'请输入用户名',icon:'none'})
    }
    else if(password==''){
      Taro.showToast({title:'请输入密码',icon:'none'})
    }
    else if(!checked){
      Taro.showToast({title:'请先阅读协议',icon:'none'})
    }
  }

  return (
    <View className='index'>
      <View className="index-cell">
        <View><Input placeholder="请输入用户名" value={user_name} onInput={e => setUsername(e.detail.value)} /><Text onClick={register}>注册</Text></View>
        <View><Input password placeholder="请输入密码" value={password} onInput={e => setPassword(e.detail.value)}/><Text>忘记密码?</Text></View>
      </View>
      <View className='important'>
        <Icon size='16' type='success' color={checked?'#D02530':'#fff'} className='checkBox' onClick={check}/>
          我已阅读并同意 
          <Text>《用户服务协议》</Text>
          与
          <Text>《隐私条款》</Text>
      </View>
      <Button className='login' id='login' onClick={login}>登 录</Button>
    </View>
  )
}

const hoc = connect(({ login }) => ({
  data:login
}), (dispatch) => ({
  userlogin(data){
    dispatch(login(data))
  }
}))

export default hoc(Login)

